package com.weetop.cfw.mine.fragment

import android.view.View
import android.widget.Toast
import com.blankj.utilcode.util.ToastUtils
import com.kongzue.dialog.v3.MessageDialog
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.weetop.cfw.R
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.ui.fragment.CommonBaseFragment
import com.weetop.cfw.bean.ErrorBean
import com.weetop.cfw.bean.MyCoursesBean
import com.weetop.cfw.bean.TestBean
import com.weetop.cfw.callback.RxJavaCallBack
import com.weetop.cfw.mine.activity.ConfirmationOfOrderActivity
import com.weetop.cfw.mine.adapter.CoursesPurchasedByUsersListAdapter
import com.weetop.cfw.utils.RetrofitUtils
import com.weetop.cfw.utils.RxJavaUtils
import kotlinx.android.synthetic.main.fragment_user_courses.*

/**
 * 全部课程订单界面
 */
class AllCoursesFragment:CommonBaseFragment(),OnRefreshLoadMoreListener {

    private lateinit var coursesPurchasedByUsersListAdapter:CoursesPurchasedByUsersListAdapter

    private var currentPageNumber = 1//当前数据的页数
    private var isRefreshing = false//是否处在刷新状态
    private var isLoadingMore = false//是否处在加载更多状态
    private var totalCount = 0//数据总条数

    private val allCoursesList = ArrayList<MyCoursesBean.DataBean>()

    private lateinit var cancelCourseOrderDialog:MessageDialog

    override fun getLayoutId() = R.layout.fragment_user_courses

    override fun initView() {

    }

    override fun initData() {
        userCoursesRefreshLayout.setEnableAutoLoadMore(false)
        userCoursesRefreshLayout.setOnRefreshLoadMoreListener(this)

        coursesPurchasedByUsersListAdapter = CoursesPurchasedByUsersListAdapter(R.layout.my_course_item_layout,allCoursesList)
        coursesPurchasedByUsersListAdapter.emptyView = emptyView
        coursesPurchasedByUsersListAdapter.setOnItemChildClickListener { adapter, view, position ->
            courseListItemClick(view,position)
        }
        userCoursesRV.adapter = coursesPurchasedByUsersListAdapter

        userVisibleHint = true
    }

    /**
     * 订单列表item中的按钮被点击
     */
    private fun courseListItemClick(view:View,position:Int){
        when(view.id){
            R.id.btnCancelCourseOrder -> showCancelCourseOrderDialog(position)
            R.id.btnAtOncePay -> ConfirmationOfOrderActivity.startConfirmationOfOrderActivity(context!!,allCoursesList[position].orderid,allCoursesList[position].infoid)
        }
    }

    /**
     * 展示取消课程订单的对话框
     */
    private fun showCancelCourseOrderDialog(position:Int){
        cancelCourseOrderDialog = MessageDialog.build(context as CommonBaseActivity).setTitle("提示")
            .setMessage("确定要取消该订单吗？")
            .setOkButton("确定取消")
            .setCancelButton("暂不取消")
            .setOnOkButtonClickListener { baseDialog, v ->
                cancelCourseOrder(position)
                true
            }
        cancelCourseOrderDialog.show()
    }

    /**
     * 取消课程订单
     */
    private fun cancelCourseOrder(position:Int){
        showLoadingDialog(activity as CommonBaseActivity,"正在取消该订单...")
        RxJavaUtils.useInSupportFragmentOnDestoryView(RetrofitUtils.getApi().cancelCourseOrder(orderId = allCoursesList[position].orderid),this,object:RxJavaCallBack<ErrorBean>(){
            override fun onSuccess(t: ErrorBean?) {
                if(t != null){
                    dismissLoadingDialog()
                    ToastUtils.showShort("课程订单取消成功")
                    if(cancelCourseOrderDialog.isShow){
                        cancelCourseOrderDialog.doDismiss()
                    }
                    userCoursesRefreshLayout.autoRefresh()
                }
            }

            override fun onRequestError(t: ErrorBean?) {
                super.onRequestError(t)
                dismissLoadingDialog()
            }
        })
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
       if(allCoursesList.size >= totalCount){
           ToastUtils.showShort("暂无更多数据")
           userCoursesRefreshLayout.finishLoadMoreWithNoMoreData()
       }else{
           isLoadingMore = true
           getAllCoursesOrder(currentPageNumber + 1)
       }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        isRefreshing = true
        getAllCoursesOrder(1)
    }

    override fun lazyLoadData() {
        if(isFirstLoadData){
            getAllCoursesOrder(currentPageNumber)
        }
    }

    /**
     * 获取所有的课程订单列表
     */
    private fun getAllCoursesOrder(tempCurrentPageNumber:Int){
        showLoadingDialog(activity!! as CommonBaseActivity,"正在获取全部课程订单列表...")
        RxJavaUtils.useInSupportFragmentOnDestoryView(RetrofitUtils.getApi().getMyCoursesList(status = -1,curpage = tempCurrentPageNumber,pagesize = 10),this,object:RxJavaCallBack<MyCoursesBean>(){

            override fun onSuccess(t: MyCoursesBean?) {
                if(t != null){
                    dismissLoadingDialog()
                    isFirstLoadData = false
                    totalCount = t.records
                    if(isRefreshing){
                        allCoursesList.clear()
                        allCoursesList.addAll(t.data)
                        coursesPurchasedByUsersListAdapter.notifyDataSetChanged()
                        userCoursesRefreshLayout.finishRefresh(true)
                        if(t.data.size > 0){
                            currentPageNumber = 1
                        }
                        isRefreshing = false
                        return
                    }
                    if(isLoadingMore){
                        allCoursesList.addAll(t.data)
                        coursesPurchasedByUsersListAdapter.notifyDataSetChanged()
                        userCoursesRefreshLayout.finishLoadMore(true)
                        if(t.data.size > 0){
                            currentPageNumber += 1
                        }
                        isLoadingMore = false
                        return
                    }

                    allCoursesList.addAll(t.data)
                    coursesPurchasedByUsersListAdapter.notifyDataSetChanged()
                }
            }

            override fun onRequestError(t: MyCoursesBean?) {
                super.onRequestError(t)
                dismissLoadingDialog()
                userCoursesRefreshLayout.finishRefresh(false)
                userCoursesRefreshLayout.finishLoadMore(false)
            }

        })
    }
}